#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/2/14 17:57
# @Author  : XH
# @File    : get_token.py
# @Software: PyCharm
import requests
from dotenv import set_key

from common.handle_log import mylog
from common.handle_path import CONF_DIR
from common.handle_yaml import HandleYaml

"""
请求头的token信息在这里进行封装
"""

USERNAME = HandleYaml("env_config.yaml").read_yaml()["login"]["username"]
PASSWORD = HandleYaml("env_config.yaml").read_yaml()["login"]["password"]
deault = HandleYaml("env_config.yaml").read_yaml()["login"]["host"]
HOST = HandleYaml("env_config.yaml").read_yaml()["env"][deault]
PATH = HandleYaml("env_config.yaml").read_yaml()["login"]["path"]
TOKEN_URL = HOST + PATH

def get_token(user = USERNAME,password = PASSWORD):
    """
    获取新的 Token 并保存到环境变量
    """
    if not USERNAME or not PASSWORD:
        mylog.debug("用户名或密码未配置，请检查 config.yaml 文件。")
        return None
    # proxies = {
    #     "http": "http://127.0.0.1:8888",
    #     "https": "http://127.0.0.1:8888",
    # }
    # 发送请求以获取 Token
    response = requests.post(TOKEN_URL,data={
        "account": user,
        "password": password
    },verify=False)
    mylog.debug(f"Request URL: {TOKEN_URL}")
    if response.status_code == 200:
        # 假设响应中返回的是 JSON 格式的数据，包含 token
        mylog.debug(response.json())
        token = response.json().get('data').get("token")
        if token:
            # 将 Token 保存到 .env 文件中
            set_key(f'{CONF_DIR}/.env', 'ACCESS_TOKEN', token)
            mylog.info("Token 获取成功并已保存。")
            return token
        else:
            mylog.error("响应中未找到 Token。")
            return None
    else:
        mylog.error(f"获取 Token 失败，状态码: {response.status_code}")
        return None

def get_cookie():
    """
    获取新的 Token 并保存到环境变量
    """
    if not USERNAME or not PASSWORD:
        mylog.debug("用户名或密码未配置，请检查 config.yaml 文件。")
        return None
    # proxies = {
    #     "http": "http://127.0.0.1:8888",
    #     "https": "http://127.0.0.1:8888",
    # }
    # 发送请求以获取 Token
    response = requests.post(TOKEN_URL,json={
        "username": USERNAME,
        "password": PASSWORD
    },verify=False)
    mylog.debug(f"Request URL: {TOKEN_URL}")
    if response.status_code == 200:
        # 获取cookies值
        cookies = response.cookies
        return cookies


if __name__ == "__main__":
    # # 调用函数获取 Token
    A = get_token()
    print(A)
    # A = get_cookie()
    # print(A)
    # 加载现有的环境变量（如果存在）
    # load_dotenv()
    # a = os.getenv('ACCESS_TOKEN')
    # print(a)